package com.zhugang.week07;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * @program algorithms
 * @description: topKFrequent
 * @author: chanzhugang
 * @create: 2022/08/01 17:58
 */
public class TopKFrequent {

    /**
     * 347 前K个高频元素
     *
     * @param nums
     * @param k
     * @return
     */
    public int[] topKFrequent(int[] nums, int k) {
        // Map统计出现的频率， 小顶堆处理数据
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int num : nums) {
            int count = 1;
            if (countMap.containsKey(num)) {
                count += countMap.get(num);
            }
            countMap.put(num, count);
        }
        // 小顶堆
        PriorityQueue<QElement> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.count));

        for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
            Integer num = entry.getKey();
            Integer count = entry.getValue();
            if (queue.size() < k) {
                queue.offer(new QElement(num, count));
            } else {
                if (queue.peek().count < count) {
                    // 替换频率少的
                    queue.poll();
                    queue.offer(new QElement(num, count));
                }
            }
        }

        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = queue.poll().val;
        }
        return result;
    }


    private class QElement {
        int val;
        int count;

        public QElement(int val, int count) {
            this.val = val;
            this.count = count;
        }
    }
}